from skillchallenge.models import *
import EventEngine
import CodeEngine
import LocationEngine

class NPCEngine:
    
    NPC_MOVE = 'npc move'
    SEE = 'see_npc'
    SEE_MOVE = 'see move'
    
    event_engine = EventEngine.EventEngine()
    code_engine = CodeEngine.CodeEngine()
    location_engine = LocationEngine.LocationEngine()
    
    def create_npc(self, name):
        if Name.objects.filter(text=name).count() == 0:
            name_obj = Name.objects.create(text=name)
        else:
            print Name.objects.filter(text=name)
            name_obj = Name.objects.filter(text=name)[0]
        return Character.objects.create(name = name_obj, npc=True)
        
    def create_move(self, npc, location):
        event = self.event_engine.add_event(preconditions =[self.code_engine.create_always_fail_precon()],
                                           info = self.__info__(self.NPC_MOVE, npc, location))
        if not location.initial:          
            event.actions.add(self.code_engine.create_fire_event_if_ok_action(self.event_engine.add_event(
                preconditions = [self.code_engine.create_always_fail_precon(), self.is_in_same_precon(npc)],
                actions = [self.code_engine.create_message_action('you see ' + npc.name.text + ' moving to ' + location.name + '.')],
                online=True, info=self.__info__(self.SEE_MOVE, npc, location))))

        event.save()
        return event
    
    def create_see(self, npc):
        setq = 'Q(timestamp__isnull = False)'
        q = 'Q(info__startswith = "' + self.location_engine.MOVE + '")|Q(info__startswith = "' + self.location_engine.INITIAL_MOVE + '")'           
        return self.event_engine.add_event(preconditions = [self.code_engine.create_latest_event_precon(setq, q), self.is_in_same_precon(npc)],
                             actions = [self.code_engine.create_message_action('you see ' + npc.name.text + '.')],
                             recurring = True, online=True, info=self.__info__(self.SEE, npc))
    
    def is_in_same_precon(self, npc):
        moving = 'Q(info__istartswith="' + self.NPC_MOVE + '")'
        p_moving = self.location_engine.player_moving()
        property = "info.split(':').pop()"
        return self.code_engine.create_compare_event_precon(moving, p_moving, property)
             
    def __info__(self, info, *args):
        return info + ":" + ":".join([str(arg.id) for arg in args])